package cn.south.campus.admin.campus.service.impl;

import cn.south.campus.admin.campus.mapper.ConfigMapper;
import cn.south.campus.admin.campus.model.entity.Config;
import cn.south.campus.admin.campus.model.req.ConfigReq;
import cn.south.campus.admin.campus.model.vo.ConfigVo;
import cn.south.campus.admin.campus.service.ConfigService;
import cn.south.campus.common.utils.HttpUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 系统配置表 服务实现类
 * </p>
 *
 * @author chow
 * @since 2024-12-13
 */
@Service
public class ConfigServiceImpl extends ServiceImpl<ConfigMapper, Config> implements ConfigService {

    @Value("${campus.url}")
    private String businessUrl;

    @Resource
    private ConfigMapper configMapper;

    @Override
    public IPage<ConfigVo> pageQuery(ConfigReq req) {
        LambdaQueryWrapper<Config> wrapper = new LambdaQueryWrapper<Config>()
                .eq(StringUtils.hasText(req.getConfigType()), Config::getConfigType, req.getConfigType())
                .like(StringUtils.hasText(req.getConfigName()), Config::getConfigName, req.getConfigName())
                .like(StringUtils.hasText(req.getConfigKey()), Config::getConfigKey, req.getConfigKey());
        return configMapper.selectPage(req.getPageDto(), wrapper).convert(ConfigVo::convert);
    }

    @Override
    public void insert(ConfigVo config) {
        Config one = configMapper.selectOne(new LambdaQueryWrapper<Config>().eq(Config::getConfigKey, config.getConfigKey()));
        if (one != null) {
            throw new RuntimeException("配置项已存在");
        }
        configMapper.insert(ConfigVo.convert(config));
    }

    @Override
    public void delete(Long id) {
        configMapper.deleteById(id);
    }

    @Override
    public void modify(ConfigVo configVo) {
        configMapper.updateById(ConfigVo.convert(configVo));
    }

    @Override
    public ConfigVo detail(Long id) {
        return ConfigVo.convert(configMapper.selectById(id));
    }

    @Override
    public void refreshCache(String key) {
        Map<String, Object> req = new HashMap<>();
        req.put("key", key);
        HttpUtils.getReq(req, businessUrl + "/config/refreshCache");
    }
}
